<template>
  <div>
    <div class="supplier" v-if="!roleAddShow && !dataAddShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['system:role:query']"
          class="btn search"
          @click="getRoleList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-hasPermi="['system:role:add']"
          class="btn search"
          @click="
            roleAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model="params.roleName"
            class="search-input"
            placeholder="请输入角色名称"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.roleKey"
            class="search-input"
            placeholder="请输入权限字符"
          ></el-input>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.status"
            placeholder="请选择角色状态"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="创建开始日期"
            end-placeholder="创建结束日期"
          ></el-date-picker>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="roleList"
        border
        height="64vh"
        :header-cell-style="{ 'text-align': 'center', background: 'red' }"
      >
        <!-- 操作模式 -->
        <el-table-column
          label="操作"
          :show-overflow-tooltip="true"
          width="210px"
        >
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                title="编辑"
                v-hasPermi="['system:role:edit']"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-hasPermi="['system:role:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-hasPermi="['system:role:edit']"
                title="数据权限"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('dataPermission', row)"
              >
                <CircleCheck />
              </el-icon>
              <el-icon
                v-hasPermi="['system:role:edit']"
                title="分配用户"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('allotUser', row)"
              >
                <User />
              </el-icon>
              <el-icon
                v-hasPermi="['system:role:remove']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column label="角色编号" prop="roleId" width="150" />
        <el-table-column
          label="角色名称"
          prop="roleName"
          :show-overflow-tooltip="true"
          width="350"
        />
        <el-table-column
          label="权限字符"
          prop="roleKey"
          :show-overflow-tooltip="true"
          width="150"
        />
        <el-table-column label="显示顺序" prop="roleSort" width="100" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="创建人"
          align="center"
          key="createBy"
          prop="createBy"
          width="100"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getRoleList"
      />
    </div>
    <RoleAdd
      v-if="roleAddShow"
      ref="roleAddRef"
      v-model:roleAddShow="roleAddShow"
      @updateEvaluateAddShow="evaluateAddShow = false"
      @refreshList="getRoleList"
      :pageType="pageType"
    />
    <Data
      v-if="dataAddShow"
      ref="dataAddRef"
      v-model:dataAddShow="dataAddShow"
      @refreshList="getRoleList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup name="Role">
import RoleAdd from "./roleAdd";
import Data from "./data";
import { getDictsApi, fileDownload } from "@/api/dict";
import { deleteContractApi } from "@/api/information/contract";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addRole,
  changeRoleStatus,
  dataScope,
  delRole,
  getRole,
  listRole,
  updateRole,
  deptTreeSelect,
} from "@/api/system/role";
import {
  roleMenuTreeselect,
  treeselect as menuTreeselect,
} from "@/api/system/menu";
const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const open = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const deptOptions = ref([]);
const openDataScope = ref(false);
const menuRef = ref(null);
const deptRef = ref(null);
// 搜索参数
const params = reactive({
  roleName: undefined,
  roleKey: undefined,
  status: undefined,
  pageNum: 1,
  pageSize: 50,
});
const loading = ref(false);
const roleAddShow = ref(false);
const dataAddShow = ref(false);
const evaluateAddShow = ref(false);
const roleList = ref([]);
const total = ref(0);
const roleAddRef = ref(null);
const dataAddRef = ref(null);
const pageType = ref("");
const templateList = ref([]);

const getRoleList = async () => {
  try {
    loading.value = true;
    listRole(proxy.addDateRange(params, dateRange.value)).then((response) => {
      roleList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  } catch {
    loading.value = false;
  }
};

/** 角色状态修改 */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.roleName + '"角色吗?')
    .then(function () {
      return changeRoleStatus(row.roleId, row.status);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
}

const handleOperate = async (type, row) => {
  switch (type) {
    case "edit":
      roleAddShow.value = true;
      pageType.value = "edit";
      nextTick(() => {
        roleAddRef.value.handleDetailInfo(row.roleId);
      });
      break;
    case "detail":
      roleAddShow.value = true;
      pageType.value = "detail";
      nextTick(() => {
        roleAddRef.value.handleDetailInfo(row.roleId);
      });
      break;
    case "dataPermission":
      dataAddShow.value = true;
      pageType.value = "edit";
      nextTick(() => {
        dataAddRef.value.handleDetailInfo(row.roleId);
      });
      break;

    case "allotUser":
      router.push("/system/role-auth/user/" + row.roleId);
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该角色，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await delRole(row.roleId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getRoleList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};
const fileDown = (row) => {
  const res = fileDownload(row.url);
  var debug = res;
  if (debug) {
    var elink = document.createElement("a");
    elink.download = row.name;
    elink.style.display = "none";
    var blob = new Blob([debug], { type: "application/octet-stream" });
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    document.body.removeChild(elink);
  } else {
    this.$message.error($t("common.DownloadException"));
  }
};

/** 根据角色ID查询部门树结构 */
function getDeptTree(roleId) {
  return deptTreeSelect(roleId).then((response) => {
    deptOptions.value = response.depts;
    return response;
  });
}

async function getDicts() {
  await getDictsApi("contract_template_type").then((res) => {
    // 模板
    if (res.code === 200) {
      templateList.value = res.data;
    }
  });
}

// -----------------------------------  序号  ----------------------------------
function indexMethod(index) {
  // 当前页码
  const currentPage = params.pageNum;
  // 每页显示的数据条数
  const pageSize = params.pageSize;
  // 当前行的实际索引
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  // 如果当前行的索引大于等于当前页的最大索引，
  // 则使用当前行的实际索引，否则使用当前行的原始索引
  return truelndex;
}

onMounted(() => {
  getRoleList();
  getDicts();
});
</script>
<style>
.confirmBtnClass {
  color: #fff;
  width: 90px;
  height: 34px;
  background: #007cef;
}
.confirmBtnClass:hover,
.confirmBtnClass:active,
.confirmBtnClass:focus {
  color: #fff;
  background: #007cef;
}
.cancelBtnClass {
  border: 1px solid #999999;
  color: #333333;
  width: 90px;
  height: 34px;
  background: #f3f3f3;
}
.cancelBtnClass:hover,
.cancelBtnClass:active,
.cancelBtnClass:focus {
  border: 1px solid #999999;
  color: #333333;
  background: #f3f3f3;
}
</style>
<style lang="scss" scoped>
:deep(.table-header) {
  background-color: #f8faff !important;
}

.supplier {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .search {
    display: flex;
    margin-bottom: 20px;
    .search-item {
      margin-right: 20px;
    }
    .search-input {
      width: 200px;
      height: 34px;
    }
  }
  /* .search-button {
    position: fixed;
    top: 110px;
    right: 60px;
    display: flex;
    .btn {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 90px;
      height: 34px;
      padding: 10px;
      // margin-right: 20px;
      font-size: 14px;
      border-radius: 4px;
      user-select: none;
      cursor: pointer;
    }
    .btn.search {
      color: #fff;
      background: rgba(0, 124, 239, 1);
      &:hover {
        background: rgba(0, 124, 239, 0.85);
      }
    }
    .btn.add {
      border: none;
      color: #fff;
      background: rgba(255, 159, 0, 1);
      &:hover {
        background: rgba(255, 159, 0, 0.85);
      }
    }
    .btn.reset {
      color: rgba(43, 193, 123, 1);
      background: rgba(43, 193, 123, 0.05);
      border: 1px solid rgba(43, 193, 123, 1);
      &:hover {
        background: rgba(43, 193, 123, 0.2);
      }
    }
    .icon {
      margin-right: 6px;
    }
  } */
  .table-operate {
    display: flex;
    justify-content: space-around;
    .table-icon {
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
  }
  .pagination {
    margin-top: 20px;
  }
  :deep(.el-table) {
    th.el-table__cell {
      font-size: 14px;
      font-weight: 400;
      height: 40px;
      color: #333333;
      background: #f8faff !important;
    }
    // 表格高度
    .el-table__cell {
      padding: 0;
      height: 40px;
    }
  }
  :deep(.el-table--large .cell) {
    padding: 0 20px 0 20px !important;
  }
}
</style>
